package com.yu.crm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.crm.domain.pojo.*;
import com.yu.crm.domain.request.TTicketStatus;
import com.yu.crm.domain.request.TTicketinfo;
import com.yu.crm.domain.response.ResultResponse;
import com.yu.crm.mapper.ShiftMapper;
import com.yu.crm.mapper.TicketinfoMapper;
import com.yu.crm.service.ITicketinfoService;
import com.yu.crm.utils.DateUtil;
import com.yu.crm.utils.TicketUtil;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.valid.ValidatorHelpers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zds
 * @since 2021-03-15
 */
@Service
public class TicketinfoService extends ServiceImpl<TicketinfoMapper, Ticketinfo> implements ITicketinfoService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CrmDeviceService crmDeviceService;

    @Autowired
    private GateService gateService;

    @Autowired
    private ShiftService shiftService;

    @Autowired
    private TicketinfoMapper ticketinfoMapper;

    public void deleteByIds(String ids) {
        try {
            String substring = ids.substring(0, ids.length());
            String[] result = substring.split(",");
            for (String s : result) {
                Ticketinfo ticketinfo = baseMapper.selectById(Long.valueOf(s));
                if (DataHelpers.isNotEmpty(ticketinfo)) {
                    ticketinfo.setIsDeleted(1);
                    ValidatorHelpers.validateDataSave(baseMapper.updateById(ticketinfo));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    public Ticketinfo infoById(Long id) {
        try {
            return baseMapper.selectById(id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    /**
     * 新增或修改票务信息
     *
     * @param ticketinfo
     */
    public Boolean addOrUpdate(Ticketinfo ticketinfo) {

        try {
            if (DataHelpers.isNotEmpty(ticketinfo.getOid())) {

                Ticketinfo ticketinfo1 = baseMapper.selectById(ticketinfo.getOid());
                if (!DataHelpers.isNotEmpty(ticketinfo1)) {
                    throw new GeneralException("票务信息有误");
                }
                //修改
                ValidatorHelpers.validateDataSave(baseMapper.updateById(ticketinfo));
                return true;
            } else {
                //新增
                ValidatorHelpers.validateDataSave(baseMapper.insert(ticketinfo));

                //实时推送数据
                pushTicketData(ticketinfo);

                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    public List<Ticketinfo> getPage(String stationName, String condition) {
        QueryWrapper<Ticketinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        if (DataHelpers.isNotEmptyString(stationName)) {
            queryWrapper.eq("station_name", stationName);
        }
        if (DataHelpers.isNotEmptyString(condition)) {
            queryWrapper.and(i -> i.like("station_name", condition)
            );
        }
        return baseMapper.selectList(queryWrapper);
    }

    public IPage<Ticketinfo> getPage(Page<Ticketinfo> page, String stationName, String condition) {
        QueryWrapper<Ticketinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        if (DataHelpers.isNotEmptyString(stationName)) {
            queryWrapper.eq("station_name", stationName);
        }
        if (DataHelpers.isNotEmptyString(condition)) {
            queryWrapper.and(i -> i.like("station_name", condition)
            );
        }
        return baseMapper.selectPage(page, queryWrapper);
    }

    public Integer selectTicket(String identityId, Integer type, String deviceId) {
        //刷身份证
        Ticketinfo ticketinfo = null;
        if (0 == type) {
            ticketinfo = baseMapper.selectOne(new QueryWrapper<Ticketinfo>().eq("identity_id", identityId));
        } else {
            //刷车票条码或是二维码
            ticketinfo = baseMapper.selectOne(new QueryWrapper<Ticketinfo>().eq("ticket_id", identityId));
        }
        if (null == ticketinfo) {
            //未购票
            return 3;
        }
        LocalDateTime busStartTime = ticketinfo.getBusStartTime();
        Date busDate = DateUtil.localDateTime2Date(busStartTime);
        if (busDate.getDate() == new Date().getDate()) {
            Long t = DateUtil.localDateTime2Date(busStartTime).getTime() - new Date().getTime();
            Long gate = gateService.getOne(new QueryWrapper<Gate>().eq("device_code", deviceId)).getId();
            String shiftNum = shiftService.getOne(new QueryWrapper<Shift>()
                    .eq("shift_num", ticketinfo.getBusNum())).getTicketGate();
            String[] split = shiftNum.substring(0, shiftNum.length()).split(",");//以逗号分割
            for (String string2 : split) {
                if (gate.equals(Long.parseLong(string2))) {
                    if (gate > 3) {
                        if (t > 0 && t <= 10 * 60 * 1000) {
                            //可以开闸
//                    crmDeviceService.openDeviceByDeviceCode(deviceId);
                            pushData(gate, ticketinfo, deviceId);
                            return 0;
                        }
                    }
                    if (t > 0 && t <= 30 * 60 * 1000) {
                        //可以开闸
//                    crmDeviceService.openDeviceByDeviceCode(deviceId);
                        pushData(gate, ticketinfo, deviceId);
                        return 0;
                    }
                    //进站时间未到或者时间已过
                    return 1;
                }
            }
            return 2;
        }
        //进站时间未到
        return 1;

    }

    /**
     * 推送票务信息
     *
     * @param ticketinfo
     */
    private static void pushTicketData(Ticketinfo ticketinfo) {
        TTicketinfo tTicketinfo = new TTicketinfo();
        tTicketinfo.setID(ticketinfo.getId());
        tTicketinfo.setBUS_NUM(ticketinfo.getBusNum());
        tTicketinfo.setBUS_START_TIME(ticketinfo.getBusStartTime());
        tTicketinfo.setBUY_TIME(ticketinfo.getBuyTime());
        tTicketinfo.setCERTI_TYPE(ticketinfo.getCertiType());
        tTicketinfo.setDEST_STATION_NAME(ticketinfo.getDestStationName());
        tTicketinfo.setIDENTITY_ID(ticketinfo.getIdentityId());
        tTicketinfo.setNAME(ticketinfo.getName());
        tTicketinfo.setPRICE(ticketinfo.getPrice());
        tTicketinfo.setSEAT_NUM(ticketinfo.getSeatNum());
        tTicketinfo.setSTART_STATION_NAME(ticketinfo.getStationName());
        tTicketinfo.setSTATION_CODE(ticketinfo.getStationCode());
        tTicketinfo.setSTATUS(ticketinfo.getStatus());
        tTicketinfo.setTICKETID(ticketinfo.getTicketId());
        tTicketinfo.setCHECK_ENTRANCE(ticketinfo.getCheckEntrance());
        tTicketinfo.setWAIT_ROOM_NUM(ticketinfo.getWaitRoomNum());
        tTicketinfo.setINSERT_TIME(ticketinfo.getInsertTime());
        String urlPath = "http://58.49.165.122:26040/WebSer_kyz/get_kljjjj2109www_T_TICKETINFO.aspx";
//        String urlPath = "http://localhost:8888/data_sync";
//        String param = "attendanceRecor=" + JSONArray.toJSONString(tTicketinfo);
        String param = "T_TICKETINFO=" + JSONArray.toJSONString(tTicketinfo);
        TicketUtil.push(urlPath, param);
    }

    /**
     * 推送检票状态信息
     *
     * @param gate
     * @param ticketinfo
     * @param deviceId
     */
    private static void pushData(Long gate, Ticketinfo ticketinfo, String deviceId) {
        TTicketStatus tTicketStatus = new TTicketStatus();
        if (gate > 3) {
            tTicketStatus.setOPERATION_STATE("3");
            tTicketStatus.setCOUNTNUM(2);
        } else {
            tTicketStatus.setOPERATION_STATE("1");
            tTicketStatus.setCOUNTNUM(1);
        }
        tTicketStatus.setID(ticketinfo.getId().toString());
        tTicketStatus.setTICKET_SIGN(ticketinfo.getTicketId());
        tTicketStatus.setCARD_TYPE(ticketinfo.getCertiType());
        tTicketStatus.setCARD_NUM(ticketinfo.getIdentityId());
        tTicketStatus.setOPERATION_TIME(DateUtil.date2LocalDateTime(new Date()));
        tTicketStatus.setBRAKE_MACHINE(deviceId);
        tTicketStatus.setSTATIONCODE(ticketinfo.getStationCode());
        tTicketStatus.setWAITING_ROOM_NUM(ticketinfo.getWaitRoomNum());
        tTicketStatus.setSYNCHRONOUS(true);
        String urlPath = "http://localhost:8888/data_sync";
        String param = "attendanceInfos=" + JSONArray.toJSONString(tTicketStatus);
        TicketUtil.push(urlPath, param);

    }

    @Override
    public void deleteByTime() {
        ticketinfoMapper.deleteByTime();
    }
}
